<template>
	<view class="bigView">
		<!-- <view class="circle-countdown-wrapper"> -->
		    <!-- 画布元素 -->
		    <canvas
		      canvas-id="countdownCanvas"
		      class="circle-countdown"
		      :style="{ width: '180rpx', height: '180rpx' }"
			  v-if="countdown>0 && type == 1 && Object.keys(this.userInfo).length>0"
		    ></canvas>
		    <!-- 开始倒计时按钮 -->
		    <!-- <button @tap="startCountdown2">开始倒计时</button> -->
		  <!-- </view> -->
		<view style="padding: 16px;overflow-y: auto;">
			<!-- <rich-text :nodes="htmlValue"></rich-text> -->
			<!-- <u-parse :content="htmlValue" :lazyLoad="true"></u-parse> -->
			<view class="titleView">{{result.theme}}</view>
			<view class="publishDateView" style="margin-top: 5px;margin-bottom: 5px;">{{result.publishDate}}</view>
			<view class="publishDateView" style="color: #3C6D9B;" v-if="result.department">部门：{{result.department}}</view>
			<view class="publishDateView" style="color: #3C6D9B;" v-if="result.provider">提供人：{{result.provider}}</view>
			<view class="publishDateView" style="color: #3C6D9B;" v-if="result.approver">批准人：{{result.approver}}</view>
			
			<view class="htmlView">
				<u-parse :content="htmlValue" class="htmlView"></u-parse>
				<!-- <rich-text :nodes="htmlValue" class="htmlView"></rich-text>
				<view v-html="htmlValue" class="htmlView"></view> -->
			</view>
			<!-- <mp-html :content="htmlValue" /> -->
			<view class="bottomView" v-if="type==1">
				<view></view>
				<view style="display: flex;flex-direction: row;padding-right: 10px;align-items: center;font-size: 14px;">
					<button open-type="share" class="shareBtn" style="border:none;color: black;" plain type="primary" v-if="Object.keys(userInfo).length>0">
					<!-- 分享 -->
						<u-icon name="share" size="20"></u-icon>
					</button>
					<view style="margin-right: 20px;" @click="shareHandle(item)" v-else>
						<u-icon name="share" size="20"></u-icon>
					</view>
					<view @click="giveThumbsHandle(item)">
						<u-icon name="heart" size="20"></u-icon>
					</view>
				</view>
			</view>
		</view>
		<view></view>
		<!-- <view v-if="remainingTime>0 && type == 1 && Object.keys(this.userInfo).length>0" style="right: 20rpx;bottom: 60rpx;display: flex;align-items: center;position: fixed;color:#FFFFFF;justify-content: center;">
			{{remainingTime}}
		</view> -->
	</view>
</template>

<script>
	import noti from '@/api/noti.js'
	import news from '@/api/news.js'
	export default{
		components:{
			
		},
		data(){
			return {
				bottom:0,
				type:0,//
				currentId:'',
				result:{},
				htmlValue:'',
				timer: null,
				timestamp:15,
				remainingTime: 15, // 60 秒
				userInfo:{},
				
				totalSeconds: 15, // 总倒计时秒数
				countdown: 15, // 当前倒计时秒数
				timer: null, // 定时器 ID
				canvasWidth: 80, // 画布宽度
				canvasHeight: 80, // 画布高度
				radius: 35, // 圆形半径
				circumference: 0, // 圆形周长
				dashoffset: 0, // 进度条偏移量
				ctx: null, // 画布上下文
				isAnimating: false // 动画状态标志
			}
		},
		mounted() {
			uni.getSystemInfo({success: (e) => {
				let custom = wx.getMenuButtonBoundingClientRect();
				this.bottom = custom.bottom;
			}})
			this.$nextTick(() =>{
				
				// 获取画布上下文
				this.ctx = uni.createCanvasContext('countdownCanvas', this);
				// 计算圆形周长
				this.circumference = 2 * Math.PI * this.radius;
				this.dashoffset = this.circumference;
				// 绘制初始状态的圆形
				this.drawCircle();
				this.initUserInfo()
			})
		},
		onUnload() {
			this.clearIntervalFun();
		},
		onLoad(options) {
			if(options.id){
				this.type = options.type;
				this.currentId = options.id;
				this.queryByIdRequest()
			}
			// if(options.userId){
			// 	if(this.type == 1){// 嘉园风情
			// 		setTimeout(()=>{
			// 			if(Object.keys(this.userInfo).length>0 && this.userInfo.id==options.userId){//如果登录人和分享进来的是同一个人，不给它记分
			// 				return
			// 			}
			// 			news.forward({id:this.currentId,userId:options.userId}).then(res =>{
							
			// 			}).catch(err =>{
							
			// 			})
			// 		},1000)
			// 	}
			// }
			if (this.type == 1) {
				setTimeout(() => {
					this.startCountdown2();
				}, 1000)
			}
		},
		onShareAppMessage() {
			if(Object.keys(this.userInfo).length==0){
				uni.redirectTo({
					url: '/pages/login/login'
				})
				return
			}
			news.forward({id:this.currentId}).then(res =>{
				
			}).catch(err =>{
				
			})
			return{
				title: this.result.theme,
				path: '/packageHome/pages/homeDetail/index?id='+this.currentId+"&type="+this.type+"&userId="+this.userInfo.id,
				success(res) {
					console.log('分享成功', res);
					if(this.type == 1){// 嘉园风情
						news.forward({id:this.result.id}).then(res =>{
							uni.showToast({
								title:"分享成功"
							})
						}).catch(err =>{
							
						})
					}
				},
				fail(err) {
					console.error('分享失败', err);
					uni.showModal({
						title:err
					})
				}
			}
		},
		onShareTimeline() {
			return {
				title: this.result.theme,
				path: '/packageHome/pages/homeDetail/index?id='+this.currentId+"&type="+this.type
			}
		},
		methods:{
			startCountdown2() {
			  if (this.isAnimating) return; // 如果动画已经在运行，则直接返回
			  this.isAnimating = true; // 标记动画开始
			  this.countdown = this.totalSeconds;
			  this.dashoffset = this.circumference;
			  this.animate();
			},
			animate() {
			  if (this.countdown <= 0) {
			    this.stopCountdown(); // 倒计时结束
			    return;
			  }
			
			  // 更新倒计时
			  this.countdown--;
			  const progress = this.countdown / this.totalSeconds;
			  this.dashoffset = this.circumference * progress;
			
			  // 绘制圆形
			  this.drawCircle();
			
			  // 继续倒计时
			  this.timer = setTimeout(() => {
			    this.animate();
			  }, 1000);
			},
			stopCountdown() {
			  clearTimeout(this.timer); // 清除定时器
			  this.timer = null;
			  this.isAnimating = false; // 标记动画结束
			  // uni.showToast({
			  //   title: '倒计时结束！',
			  //   icon: 'none'
			  // });
			  this.browseRequest()
			},
			drawCircle() {
			  if (!this.ctx) return;
			  const ctx = this.ctx;
			  const centerX = this.canvasWidth / 2;
			  const centerY = this.canvasHeight / 2;
			
			  // 清空画布
			  ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
			
			  // 绘制橘黄色背景圆
			  ctx.beginPath();
			  ctx.arc(centerX, centerY, this.radius, 0, 2 * Math.PI);
			  ctx.fillStyle = '#F5F5F5';
			  ctx.fill();
			
			  // 绘制背景圆
			  ctx.beginPath();
			  ctx.arc(centerX, centerY, this.radius, 0, 2 * Math.PI);
			  ctx.strokeStyle = '#e0e0e0';
			  ctx.lineWidth = 10;
			  ctx.stroke();
			
			  // 绘制进度圆
			  ctx.beginPath();
			  const startAngle = -Math.PI / 2;
			  // const endAngle = startAngle - 2 * Math.PI * (1 - this.dashoffset / this.circumference); // 逆时针方向
			  const endAngle = startAngle - 2 * Math.PI * (1 - this.dashoffset / this.circumference);
			  ctx.arc(centerX, centerY, this.radius, startAngle, endAngle, true); // true 表示逆时针
			  ctx.strokeStyle = this.getColor();
			  ctx.lineWidth = 10;
			  ctx.lineCap = 'round';
			  ctx.stroke();
			
			  // 绘制倒计时文本
			  ctx.font = '20px Arial';
			  ctx.fillStyle = 'black';
			  ctx.textAlign = 'center';
			  ctx.textBaseline = 'middle';
			  ctx.fillText(this.countdown, centerX, centerY);
			
			  // 绘制到画布
			  ctx.draw(true); // 使用 true 表示保留上一次绘制的内容
			},
			getColor() {
			  const ratio = this.countdown / this.totalSeconds;
			  // if (ratio > 0.6) {
			    return '#247BFD';
			  // } else if (ratio > 0.3) {
			    // return 'orange';
			  // }
			  // return 'red';
			},
			click(item) {
				this.newsListRequest(item.index+1)
			},
			sureHandle(){
				uni.navigateBack()
			},
			queryByIdRequest(){
				if(this.type==0){//通知公告
					noti.queryByIdHandle({id: this.currentId}).then(res =>{
						this.result = res;
						// this.result.publishDate = '2024年12月04 11:29'
						// this.result.department = '嘉园客服部'
						// this.result.provider = '张三'
						// this.result.approver = '李四'
						this.htmlValue = this.result.content;
					}).catch(error =>{
					
					})
				}else if(this.type==1){//新闻动态
					news.queryByIdHandle({id: this.currentId}).then(res =>{
						this.result = res;
						this.htmlValue = this.result.content;
					}).catch(error =>{
					
					})
				}
				
			},
			initUserInfo(){
				const userInfo = uni.getStorageSync("userInfo")
				if(userInfo){
					this.userInfo = JSON.parse(userInfo)
				}				
			},
			backHandle(){
				if(this.timer != null){
					clearInterval(this.timer);
				}
			},
			// 事件触发，每秒一次
			change(timestamp) {
				console.log(timestamp);
			},
			formattedTime() {
			  const seconds = this.remainingTime % 60;
			  return `${seconds < 10 ? '0' + seconds : seconds}`;
			},
			clearIntervalFun(){
			  if (this.timer != undefined && this.timer != null) {
			    clearInterval(this.timer);
			    this.timer = null;
			  }
			},
			startCountdown() {
				if(Object.keys(this.userInfo).length==0){
					return
				}
			      this.timer = setInterval(() => {
			        if (this.remainingTime > 0) {
			          this.remainingTime--;
					  console.log("-------"+this.remainingTime)
			        } else {
			          clearInterval(this.timer);
			          this.remainingTime = 0;
					  this.browseRequest()
			        }
			      }, 1000)
			},
			browseRequest(){
				if(this.type == 1){// 新闻动态
					news.browse({id:this.result.id}).then(res =>{
						
					}).catch(err =>{
					
					})
				}
				
			},
			giveThumbsHandle(){// 点赞
				if(Object.keys(this.userInfo).length==0){
					uni.redirectTo({
						url: '/pages/login/login'
					})
					return
				}
				uni.showLoading({
					title:"正在执行..."
				})
				if(this.type == 1){// 新闻动态
					news.giveThumbs({id:this.result.id}).then(res =>{
						uni.hideLoading()
						uni.showToast({
							title:"操作成功"
						})
					}).catch(err =>{
						uni.hideLoading()
					})
				}
				
			},
			shareHandle(item){
				if(Object.keys(this.userInfo).length==0){
					uni.redirectTo({
						url: '/pages/login/login'
					})
					return
				}
			},
		},
		onReady() {
			
		}
	}
</script>

<style lang="scss" scoped>
	@font-face {
		font-family: 'iconfont';
		// src: url('~@/static/iconfont2.ttf');
		// 优设标题黑字体
		src: url('https://t-tooth.oss-cn-shenzhen.aliyuncs.com/test/iconfont3.ttf') format('truetype');
		// src: url('https://t-tooth.oss-cn-shenzhen.aliyuncs.com/test/iconfont2.ttf') format('truetype');
	}
.bigView{
	width: 100vw;
	height: 100vh;
	background-color: white;//#F7F7F7;
	background-color: #F7F7F7;
	display: flex;
	flex-direction: column;
}
.titleView{
	width: 100%;
	font-size: 22px;
	color: black;
	font-weight: bold;
}
.publishDateView{
	// margin-top: 8px;
	line-height: 1.5;
	font-size: 14px;
	color: #999999;
}
.bottomView{
	width: 100%;
	height: 40px;
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
}
.htmlView{
	margin-top: 3px;
	// font-family: iconfont;
	// font-family: -apple-system, BlinkMacSystemFont,
	// 	"Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell",
	// 	"Fira Sans", "Droid Sans", "Helvetica Neue",
	// 	iconfont;
	// font-family: -apple-system, BlinkMacSystemFont,
	// 	"fangsong",
	// 	iconfont;
	// font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
	font-family: 'fangsong','Arial','SimSun','KaiTi', 'LiSu' !important;
}
.shareBtn{
	background-color: white;
	border: none;
	font-size: 14px;
}
.countDownView{
	position: fixed;
	width: 50px;
	height: 50px;
	background-color: #FFFFFF;
	right: 5px;
	bottom: 60px;
	border-radius: 25px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 12;
	box-shadow: 1px 1px #FFFFFF;
}

table, td, th {
  border-color: #ddd;
  border-width: 1px;
  border-style: solid;
}
.circle-countdown-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  // height: 100vh;
  background-color: red;
}

.circle-countdown {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 20px;
  z-index: 10;
  position: fixed;
  right: 0rpx;
  bottom: 60rpx;
  // background-color: red;
}
</style>